<!DOCTYPE HTML PUBLIC "-//ORA//DTD CD HTML 3.2//EN">
<HTML>
<HEAD>
<TITLE>[Chapter 5] 5.10 The Object and Class Classes</TITLE>
<META NAME="author" CONTENT="Pat Niemeyer and Josh Peck">
<META NAME="date" CONTENT="Tue Jul 22 18:53:07 1997">
<META NAME="form" CONTENT="html">
<META NAME="metadata" CONTENT="dublincore.0.1">
<META NAME="objecttype" CONTENT="book part">
<META NAME="otheragent" CONTENT="gmat dbtohtml">
<META NAME="publisher" CONTENT="O'Reilly &amp; Associates, Inc.">
<META NAME="source" CONTENT="SGML">
<META NAME="subject" CONTENT="Java">
<META NAME="title" CONTENT="Exploring Java">
<META HTTP-EQUIV="Content-Script-Type" CONTENT="text/javascript">
</HEAD>
<body vlink="#551a8b" alink="#ff0000" text="#000000" bgcolor="#FFFFFF" link="#0000ee">

<DIV CLASS=htmlnav>
<H1><a href='index.htm'><IMG SRC="gifs/smbanner.gif"
     ALT="Exploring Java" border=0></a></H1>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_09.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><B><FONT FACE="ARIEL,HELVETICA,HELV,SANSERIF" SIZE="-1">Chapter 5<br>Objects in Java</FONT></B></TD>
<td width=172 align=right valign=top><A HREF="ch05_11.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
</table>

&nbsp;
<hr align=left width=515>
</DIV>
<DIV CLASS=sect1>
<h2 CLASS=sect1><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-9">5.10 The Object and Class Classes</A></h2>

<P CLASS=para>
<A NAME="CH05.OBJ1"></A><A NAME="CH05.OBJ3"></A><tt CLASS=literal>java.lang.Object</tt> is the mother of all objects; it's
the primordial class from which all other classes are ultimately
derived. Methods defined in <tt CLASS=literal>Object</tt> are therefore
very important because they appear in every instance of any class,
throughout all of Java. At last count, there were nine
<tt CLASS=literal>public</tt> methods in <tt CLASS=literal>Object</tt>. Five
of these are versions of <tt CLASS=literal>wait()</tt> and
<tt CLASS=literal>notify()</tt> that are used to synchronize threads on
object instances, as we'll discuss in <A HREF="ch06_01.htm">Chapter 6, <i>Threads</i></A>. The remaining four methods are used for basic
comparison, conversion, and administration.

<P CLASS=para>
Every object has a <tt CLASS=literal>toString()</tt> method that is
called when it's to be represented as a text
value. <tt CLASS=literal>PrintStream</tt> objects use
<tt CLASS=literal>toString()</tt> to print data, as discussed in
<A HREF="ch08_01.htm">Chapter 8, <i>Input/Output Facilities</i></A>. <tt CLASS=literal>toString()</tt> is also used
when an object is referenced in a string concatenation. Here are some
examples:

<DIV CLASS=programlisting>
<P>
<PRE>
MyObj myObject = new MyObj(); 
Answer theAnswer = new Answer(); 
 
System.out.println( myObject ); 
String s = "The answer is: " + theAnswer ; 
</PRE>
</DIV>

<P CLASS=para>
<A NAME="CH05.EQUALS"></A>To be friendly, a new kind of object should override
<tt CLASS=literal>toString()</tt> and implement its own version that
provides appropriate printing functionality. Two other methods,
<tt CLASS=literal>equals()</tt> and <tt CLASS=literal>hashCode()</tt>, may
also require specialization when you create a new class.

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-9.1">Equality</A></h3>

<P CLASS=para>
<tt CLASS=literal>equals()</tt> compares whether two objects are
equivalent. Precisely what that means for a particular class is
something that you'll have to decide for yourself. Two
<tt CLASS=literal>String</tt> objects, for example, are considered
equivalent if they hold precisely the same characters in the same
sequence:

<DIV CLASS=programlisting>
<P>
<PRE>
String userName = "Joe"; 
... 
if ( userName.equals( suspectName ) )
    arrest( userName );
</PRE>
</DIV>

<P CLASS=para>
Note that using <tt CLASS=literal>equals()</tt> is *not* the 
same as: 

<DIV CLASS=programlisting>
<P>
<PRE>
// if ( userName == suspectName )      // Wrong! 
</PRE>
</DIV>

<P CLASS=para>
The above code tests to see if the two <tt CLASS=literal>String</tt> 
objects are the same object, which is sufficient but not necessary for 
them to be equivalent objects. 

<P CLASS=para>
A class should override the <tt CLASS=literal>equals()</tt> method
if it needs to implement its own notion of equality. If you have no
need to compare objects of a particular class, you don't need to
override <tt CLASS=literal>equals()</tt>.

<P CLASS=para>
Watch out for accidentally overloading
<tt CLASS=literal>equals()</tt> when you mean to override
it. <tt CLASS=literal>equals()</tt> takes an <tt CLASS=literal>Object</tt> as
an argument and returns a <tt CLASS=literal>boolean</tt> value. While
you'll probably want to check only if an object is equivalent to
an object of its own type, in order to properly override
<tt CLASS=literal>equals()</tt>, the method should accept a generic
<tt CLASS=literal>Object</tt> as its argument. Here's an example of
implementing <tt CLASS=literal>equals()</tt>:

<DIV CLASS=programlisting>
<P>
<PRE>
class Sneakers extends Shoes { 
    public boolean equals( Object arg ) { 
        if ( (arg != null) &amp;&amp; (arg instanceof Sneakers) ) { 
            // compare arg with this object to check equivalence 
            // If comparison is okay... 
            return true; 
        } 
        return false; 
    } 
    ... 
} 
</PRE>
</DIV>

<P CLASS=para>
A <tt CLASS=literal>Sneakers</tt> object can now be properly compared by
any current or future Java classes. If we had instead used a
<tt CLASS=literal>Sneakers</tt> type object as the argument to
<tt CLASS=literal>equals()</tt>, all would be well for classes that
reference our objects as <tt CLASS=literal>Sneakers</tt>, but methods that
simply use <tt CLASS=literal>Shoes</tt> would not see the overloaded
method and would compare <tt CLASS=literal>Sneakers</tt> against other
<tt CLASS=literal>Sneakers</tt> improperly.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-9.2">Hashcodes</A></h3>

<P CLASS=para>
The <tt CLASS=literal>hashCode()</tt> method returns an integer that is a
hashcode for a class instance. A hashcode is like a signature
for an object; it's an arbitrary-looking identifying number that is
(with important exceptions) generally different for different
instances of the class. Hashcodes are used in the process of storing
objects in a <tt CLASS=literal>Hashtable</tt>, or a similar kind of
collection. The hashcode is essentially an index into the collection.
See <A HREF="ch07_01.htm">Chapter 7, <i>Basic Utility Classes</i></A> for a complete discussion of
<tt CLASS=literal>Hashtable</tt> objects and hashcodes.

<P CLASS=para>
The default implementation of <tt CLASS=literal>hashCode()</tt> in
<tt CLASS=literal>Object</tt> assigns each object instance a unique
number to be used as a hashcode. If you don't override this
method when you create a new class, each instance of the class will
have a unique hashcode. This is sufficient for most objects. However,
if the class has a notion of equivalent objects, then you should
probably override <tt CLASS=literal>hashCode()</tt> so that equivalent
objects are given the same hashcode.

</DIV>

<DIV CLASS=sect2>
<h3 CLASS=sect2><A CLASS="TITLE" NAME="EXJ-CH-5-SECT-9.3">java.lang.Class</A></h3>

<P CLASS=para>
<A NAME="CH05.OBJ2"></A><A NAME="CH05.OBJ5"></A><A NAME="CH05.GET"></A>The last method of <tt CLASS=literal>Object</tt> we need to discuss 
is <tt CLASS=literal>getClass()</tt>.  This method returns a reference 
to the <tt CLASS=literal>Class</tt> object that produced the object 
instance. 

<P CLASS=para>
A good measure of the complexity of an object-oriented language
is the degree of abstraction of its class structures. We know that
every object in Java is an instance of a class, but what exactly is a
class? In C++, objects are formulated by and instantiated from
classes, but classes are really just artifacts of the compiler. Thus,
you see only classes mentioned in C++ source code, not at run-time. By
comparison, classes in Smalltalk are real, run-time entities in the
language that are themselves described by "meta-classes"
and "meta-class classes." Java strikes a happy medium between these
two languages with what is, effectively, a two-tiered system that uses
<tt CLASS=literal>Class</tt> objects.

<P CLASS=para>
Classes in Java source code are represented at run-time by
instances of the <tt CLASS=literal>java.lang.Class</tt> class. There's a
<tt CLASS=literal>Class</tt> object for every class you use; this
<tt CLASS=literal>Class</tt> object is responsible for producing instances
for its class. This may sound overwhelming, but you don't have
to worry about any of it unless you are interested in loading new
kinds of classes dynamically at run-time.

<P CLASS=para>
We can get the <tt CLASS=literal>Class</tt> associated with 
a particular object with the <tt CLASS=literal>getClass()</tt> method:

<DIV CLASS=programlisting>
<P>
<PRE>
String myString = "Foo!"
Class c = myString.getClass();
</PRE>
</DIV>

<P CLASS=para>
We can also get the Class reference for a particular class statically,
using the special <tt CLASS=literal>.class</tt> notation:

<DIV CLASS=programlisting>
<P>
<PRE>
Class c = String.class;
</PRE>
</DIV>

<P CLASS=para>
The .class reference looks like a static field that exists in every
class.  However, it is really resolved by the compiler.

<P CLASS=para>
One thing we can do with the <tt CLASS=literal>Class</tt> object 
is to ask for the name of the object's class: 

<DIV CLASS=programlisting>
<P>
<PRE>
String s = "Boofa!"; 
Class strClass = s.getClass(); 
System.out.println( strClass.getName() ); // prints "java.lang.String" 
</PRE>
</DIV>

<P CLASS=para>
Another thing that we can do with a <tt CLASS=literal>Class</tt> is 
to ask it to produce a new instance of its type of object. Continuing with 
the above example: 

<DIV CLASS=programlisting>
<P>
<PRE>
try { 
    String s2 = (String)strClass.newInstance(); 
} 
catch ( InstantiationException e ) { ... } 
catch ( IllegalAccessException e ) { ... } 
</PRE>
</DIV>

<P CLASS=para>
<tt CLASS=literal>newInstance()</tt> has a return type of
<tt CLASS=literal>Object</tt>, so we have to cast it to a reference of the
appropriate type. A couple of problems can occur here. An
<tt CLASS=literal>InstantiationException</tt> indicates we're trying
to instantiate an <tt CLASS=literal>abstract</tt> class or an
interface. <tt CLASS=literal>IllegalAccessException</tt> is a more general
exception that indicates we can't access a constructor for the
object. Note that <tt CLASS=literal>newInstance()</tt> can create only an
instance of a class that has an accessible default constructor.
There's no way for us to pass any arguments to a constructor.

<P CLASS=para>
All this becomes more meaningful when we add the capability to look 
up a <tt CLASS=literal>Class</tt> by name. <tt CLASS=literal>forName()</tt> 
is a <tt CLASS=literal>static</tt> method of <tt CLASS=literal>Class</tt> 
that returns a <tt CLASS=literal>Class</tt> object given its name as 
a <tt CLASS=literal>String</tt>: 

<DIV CLASS=programlisting>
<P>
<PRE>
try { 
    Class sneakersClass = Class.forName("Sneakers"); 
}  
catch ( ClassNotFoundException e ) { ... } 
</PRE>
</DIV>

<P CLASS=para>
A <tt CLASS=literal>ClassNotFoundException</tt> is thrown if the class 
can't be located. 

<P CLASS=para>
Combining the above tools, we have the power to load new kinds of classes 
dynamically. When combined with the power of interfaces, we can use 
new data types by name in our applications: 

<DIV CLASS=programlisting>
<P>
<PRE>
interface Typewriter { 
    void typeLine( String s ); 
    ... 
} 
 
class Printer implements Typewriter { 
    ... 
} 
 
class MyApplication { 
    ... 
    String outputDeviceName = "Printer"; 
 
    try { 
        Class newClass = Class.forName( outputDeviceName ); 
        Typewriter device = (Typewriter)newClass.newInstance(); 
        ... 
        device.typeLine("Hello..."); 
    } 
    catch ( Exception e ) { 
} 
</PRE>
</DIV>

</DIV>

</DIV>


<DIV CLASS=htmlnav>

<P>
<HR align=left width=515>
<table width=515 border=0 cellpadding=0 cellspacing=0>
<tr>
<td width=172 align=left valign=top><A HREF="ch05_09.htm"><IMG SRC="gifs/txtpreva.gif" ALT="Previous" border=0></A></td>
<td width=171 align=center valign=top><a href="index.htm"><img src='gifs/txthome.gif' border=0 alt='Home'></a></td>
<td width=172 align=right valign=top><A HREF="ch05_11.htm"><IMG SRC="gifs/txtnexta.gif" ALT="Next" border=0></A></td>
</tr>
<tr>
<td width=172 align=left valign=top>Inner Classes</td>
<td width=171 align=center valign=top><a href="index/idx_0.htm"><img src='gifs/index.gif' alt='Book Index' border=0></a></td>
<td width=172 align=right valign=top>Reflection</td>
</tr>
</table>
<hr align=left width=515>

<IMG SRC="gifs/smnavbar.gif" USEMAP="#map" BORDER=0> 
<MAP NAME="map"> 
<AREA SHAPE=RECT COORDS="0,0,108,15" HREF="../javanut/index.htm"
alt="Java in a Nutshell"> 
<AREA SHAPE=RECT COORDS="109,0,200,15" HREF="../langref/index.htm" 
alt="Java Language Reference"> 
<AREA SHAPE=RECT COORDS="203,0,290,15" HREF="../awt/index.htm" 
alt="Java AWT"> 
<AREA SHAPE=RECT COORDS="291,0,419,15" HREF="../fclass/index.htm" 
alt="Java Fundamental Classes"> 
<AREA SHAPE=RECT COORDS="421,0,514,15" HREF="../exp/index.htm" 
alt="Exploring Java"> 
</MAP>
</DIV>

</BODY>
</HTML>
